import React, { useState } from 'react'
import './index.css'


interface PictureCardProps {
    word: string;
    submit: (data: string) => void;
    audio: string;
}
export default function PictureCard({ word, submit, audio }: PictureCardProps) {
    const [imgPreview, setImgPreview] = useState('https://res.bearbobo.com/resource/upload/W44yyxvl/upload-ih56twxirei.png')
    const playAudio = () => {
        const au = new Audio(audio)
        au.play()
    }

    const updateImageData = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0]//图片的详细描述
        if (!file) return
        //预览,把本地资源转换成一个可用的地址
        return new Promise((resolve, reject) => {
            const reader = new FileReader()//文件读取器,把本地文件或图片转换成base64格式的url地址
            reader.readAsDataURL(file)//把图片的详细描述转换成一个可用的地址
            reader.onload = () => {//图片转换成功
                const data = reader.result as string//base64格式的url地址
                setImgPreview(data)//将base64格式的url地址赋值给imgPreview，展示在原来的照相机位置
                submit(data)
                resolve(data)
            }
            reader.onerror = (error) => {
                reject(error)
            }
        })
    }
    return (
        <div className='card'>
            <input id='selectImage' type="file" className='input' accept='.jpg,.png,.jpeg,.gif' onChange={updateImageData} />
            <label htmlFor="selectImage" className='upload'>
                <img src={imgPreview} alt="" />
            </label>
            <div className="word">
                {word}
            </div>
            <div className='playAudio' onClick={playAudio}>
                <img width={20} src='https://res.bearbobo.com/resource/upload/Omq2HFs8/playA-3iob5qyckpa.png' alt="" />
            </div>
        </div>
    )
}
